package com.qianfeng.smartdevice.service.impl;

import com.qianfeng.smartdevice.dto.HumtempEcharts;
import com.qianfeng.smartdevice.mapper.HumitureMapper;
import com.qianfeng.smartdevice.pojo.Humiture;
import com.qianfeng.smartdevice.service.IHumitureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class HumitureServiceImpl implements IHumitureService {

    private HumitureMapper humitureMapper;

    @Autowired
    public void setHumitureMapper(HumitureMapper humitureMapper) {
        this.humitureMapper = humitureMapper;
    }

    @Override
    @EventListener
    public void addHumiture(Humiture humiture) {
        //应该对数据进行判断,此处忽略
        humiture.setTemperature(5*(humiture.getTemperature()-32)/9);//修改温度为摄氏度
        humitureMapper.addHumiture(humiture);

    }

    @Override
    public HumtempEcharts getHumitures() {
        //我们的目的是查询出最近十分钟的温湿度数据,转换为 echrts 需要的数据,返回
        //where  uploaddate between a and b
        // new Date(System.currentTimeMillis()-10*60*1000)
        Instant now = Instant.now();//当前时间
        Instant instant = now.plusSeconds(-10*60);//向前推 10 分钟
        Date current = Date.from(now);//当前日期
        Date before = Date.from(instant);//十分钟以前的日期
        List<Humiture> humitureList = humitureMapper.findHumituresByDate(before, current);
        List<Date> times = new ArrayList<>();
        List<Double> tempList = new ArrayList<>();
        List<Double> humList = new ArrayList<>();
        humitureList.forEach(humiture -> {
            //获取到每一个的时间,放到时间集合
            times.add(humiture.getUploaddate());
            //获取每一个湿度,放到湿度集合
            humList.add(humiture.getHumidity());
            //获取每一个温度,放到温度集合
            tempList.add(humiture.getTemperature());
        });
        HumtempEcharts humtempEcharts = new HumtempEcharts(times, tempList, humList);
        return humtempEcharts;
    }
}
